<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AdminUser\Action\Admin;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Contract\AdminUserContract;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;
use MoChat\Plugin\AdminWallet\Contract\AdminWalletContract;

/**
 * 代理- 充值.
 *
 * Class Recharge.
 * @Controller
 */
class Recharge extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var AdminUserContract
     */
    protected $adminUserService;

    /**
     * @Inject
     * @var AdminWalletContract
     */
    protected $adminWalletService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/admin/adminUser/recharge", methods="post")
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        $adminUser = user();
        // 参数验证
        $this->validated($this->request->all());
        // 接收参数
        $params = [
            'id' => (int) $this->request->input('id'),
            'money' => (int) $this->request->input('money'),
        ];
        // 余额检查
        $walletBalance = $this->handleParams($params);
        // 数据操作
        Db::beginTransaction();
        try {
            // 修改代理余额
            $this->adminUserService->updateAdminUserById($params['id'], ['wallet_balance' => $walletBalance]);
            $type = $params['money'] >= 0 ? 1 : 2;
            // 创建管理员钱包流水记录
            $walletData = [
                'user_id' => $params['id'],
                'type' => $type,
                'amount' => $params['money'],
                'operator_id' => $adminUser['id'],
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $this->adminWalletService->createAdminWallet($walletData);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '代理充值失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '代理充值失败');
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required | integer | min:1 | bail',
            'money' => 'required | string | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '代理id 必填',
            'id.integer' => '代理 必需为整数',
            'id.min' => '代理 值不可小于1',
            'money.required' => '充值金额 必填',
            'money.string' => '充值金额 必需为字符串',
        ];
    }

    /**
     *  获取余额.
     * @return float 响应数组
     */
    private function handleParams(array $params): float
    {
        $walletBalance = 0;
        $info = $this->adminUserService->getAdminUserById($params['id'], ['wallet_balance']);
        $walletBalance = $info['walletBalance'] + $params['money'];
        if ($walletBalance < 0) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '充值后余额小于零，请重新输入充值金额');
        }
//        if ($params['money'] < 0) {
//            $walletBalance = $info['walletBalance'] - $params['money'];
//            if ($walletBalance < 0) {
//                throw new CommonException(ErrorCode::SERVER_ERROR, '充值后余额小于零，请重新输入充值金额');
//            }
//        }
//        if ($params['money'] >= 0) {
//            $walletBalance = $info['walletBalance'] + $params['money'];
//        }
        return $walletBalance;
    }
}
